﻿using System;
using System.Collections.Generic;
using Opalis.QuickIntegrationKit;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Collections;

namespace Active_Directory
{
    [OpalisObject("Move AD Object")]
    class MoveADObject : IOpalisObject
    {
        private ConnectionCredentials credentials;

        [OpalisConfiguration]
        public ConnectionCredentials Credentials
        {
            get { return credentials; }
            set { credentials = value; }
        }

        public void Design(IOpalisDesigner designer)
        {
            designer.AddInput("Source Object LDAP Path").WithDefaultValue("LDAP://CN=ObjectName,OU=Container,DC=Contoso,DC=Com");
            designer.AddInput("Destination Container OU LDAP Path").WithDefaultValue("LDAP://OU=DestinationContainer,DC=Contoso,DC=Com");
            designer.AddOutput("Object LDAP Path");
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {
            String originalLDAPPath = request.Inputs["Source Object LDAP Path"].AsString();
            String ContainerOULDAPPath = request.Inputs["Destination Container OU LDAP Path"].AsString();

            String objectName = originalLDAPPath.Split(',')[0].Substring(7);
            String destination = ContainerOULDAPPath.Substring(7);

            DirectoryEntry eLocation = new DirectoryEntry(originalLDAPPath, credentials.UserName + "@" + credentials.Domain, credentials.Password);
            DirectoryEntry nLocation = new DirectoryEntry(ContainerOULDAPPath, credentials.UserName + "@" + credentials.Domain, credentials.Password);
            string newName = eLocation.Name;
            eLocation.MoveTo(nLocation, newName);
            nLocation.Close();
            eLocation.Close();

            response.Publish("Object LDAP Path", "LDAP://" + objectName + "," + destination);
        }
    }
}